package com.yuncheng.oaApi.controller;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.yuncheng.oaApi.utils.GetUuIdUtils;;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.oaApi.utils.OaLocalFileUploadUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.utils.I18nUtil;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.oaApi.entity.OaWjjl;
import com.yuncheng.oaApi.service.IOaWjjlService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.oaApi.weboffice.OaWebOfficeFile;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: OA-正文文件记录接口
 * @Author: yuncheng
 * @Date: 2023-08-18
 * @Version: V1.0
 */
@Api(tags = "OA-正文文件记录接口-服务端/客户端")
@RestController
@RequestMapping("/api/spzx-oa/oaWjjl")
public class OaWjjlController extends BaseController<OaWjjl, IOaWjjlService> {

    private static final Logger log = LoggerFactory.getLogger(OaWjjlController.class);

    @Resource
    private IOaWjjlService oaWjjlService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private OaLocalFileUploadUtils oaLocalFileUploadUtils;

    @Resource
    private OaWebOfficeFile oaWebOfficeFIle;

    /**
     * 分页列表查询
     *
     * @param oaWjjl
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "OA-文件记录-分页列表查询")
    @ApiOperation(value = "OA-文件记录-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(OaWjjl oaWjjl, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<OaWjjl> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<OaWjjl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(oaWjjl.getFoaid()), OaWjjl::getFoaid, oaWjjl.getFoaid());
        queryWrapper.orderByDesc(OaWjjl::getFscsj);

        IPage<OaWjjl> pageList = oaWjjlService.page(page, queryWrapper);

        return HttpResult.ok(pageList);
    }


//    /**
//     * 添加
//     *
//     * @param oaWjjl
//     * @return
//     */
//    @AutoLog(value = "OA-文件记录-添加")
//    @ApiOperation(value = "OA-文件记录-添加")
//    //@RequiresPermissions("zw:OaWjjl:add")
//    @PostMapping(value = "/add")
//    public HttpResult<?> add(@RequestBody OaWjjl oaWjjl) {
//        HttpResult<String> result = new HttpResult(true);
//        oaWjjlService.save(oaWjjl);
//        result.setResult(oaWjjl.getId());
//        result.setMessage(I18nUtil.message("save.success"));
//        return result;
//    }

//    /**
//     * 编辑
//     *
//     * @param oaWjjl
//     * @return
//     */
//    @AutoLog(value = "OA-文件记录-编辑")
//    @ApiOperation(value = "OA-文件记录-编辑")
//    //@RequiresPermissions("zw:OaWjjl:edit")
//    @PutMapping(value = "/edit")
//    public HttpResult<?> edit(@RequestBody OaWjjl oaWjjl) {
//        oaWjjlService.updateById(oaWjjl);
//        return HttpResult.ok(I18nUtil.message("update.success"));
//    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "OA-文件记录-通过id删除")
    @ApiOperation(value = "OA-文件记录-通过id删除")
    //@RequiresPermissions("zw:OaWjjl:delete")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        oaWjjlService.removeById(id);
        return HttpResult.ok(I18nUtil.message("delete.success"));
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "OA-文件记录-批量删除")
    @ApiOperation(value = "OA-文件记录-批量删除")
    //@RequiresPermissions("zw:OaWjjl:delete")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        oaWjjlService.removeByIds(Arrays.asList(ids.split(",")));
        return HttpResult.ok(I18nUtil.message("delete.success"));
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "OA-文件记录-通过id查询")
    @ApiOperation(value = "OA-文件记录-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        OaWjjl oaWjjl = oaWjjlService.getById(id);
        return HttpResult.ok(oaWjjl);
    }

    /**
     * @Author: lhb
     * @Description : 如果在第一次上传正文没有oaid 传空字符串，并在保存或者提交后 再次调取编辑接口更新oaid
     * @DateTime:
     * @Params:
     */
    @AutoLog(value = "OA正文-上传文件")
    @ApiOperation(value = "OA正文-上传文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file", value = "文件不能为空", required = true)
    })
    @PostMapping(value = "/uploadOAzw")
    public HttpResult<?> uploadOAzw(@RequestPart("file") MultipartFile file,
                                    @RequestParam("oaid") String oaid) {
        OaWjjl oaWjjl = new OaWjjl();

        oaWjjl.setId(GetUuIdUtils.ReplaceUuId());

        if (StringUtils.isBlank(oaid)) {
            return HttpResult.error("没有绑定流程id");
        }
        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名称
        String fileName = file.getOriginalFilename();
        int startIndex = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
        fileName = fileName.substring(startIndex + 1).substring(0, fileName.indexOf("."));


        String wjccmc = fileName + wjlx;
        String newDir = OaCommonFlowConstant.OA_ZW; //文件夹名称

        String sjmc = GetUuIdUtils.generateUuid();
        String wjxnmc = sjmc + wjlx;

        oaLocalFileUploadUtils.uploadZdyzwFile(file, wjccmc, newDir); // 上传文件

        String cflj = "/" + newDir + "/" + wjccmc;
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        oaWjjl.setFwjmc(wjccmc); //文件真实名称
        oaWjjl.setFwjlx(wjlx);
        oaWjjl.setFwjccmc(wjxnmc); //文件虚拟路径
        oaWjjl.setFjdcflj(cflj);
        oaWjjl.setFscr(currentUser.getName());
        oaWjjl.setFscruserid(currentUser.getId());
        oaWjjl.setFscsj(DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        oaWjjl.setFoaid(oaid);

        oaWjjlService.save(oaWjjl);
        String id = oaWjjl.getId();
        if (StringUtils.isNotBlank(id)) {
            String czContent = "上传正文";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(oaWjjl);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(OaLogConstant.LOGS_OA_ZW, czContent, id, OaCommonFlowConstant.LOGS_SYS_TYPE_BC, OaCommonFlowConstant.LOGS_SYS_TYPE_BC);

        }
        return HttpResult.ok("上传成功");


    }


    @AutoLog(value = "OA-打开文档(可编辑)-服务端")
    @ApiOperation(value = "OA-打开文档（可编辑）-服务端")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "附件id", required = true)
    })
    @GetMapping(value = "/openFile")
    public HttpResult<?> openFile(@RequestParam("id") String id) {
        OaWjjl wjid = oaWjjlService.getById(id);
        if (wjid == null) {
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjid.getFwjlx()) && wjid.getFwjlx().equals(".pdf")) {
            return HttpResult.error("当前文档为pdf文档，请选择重新编辑文档");
        }
        String url = oaWebOfficeFIle.openFileByOazw(wjid, wjid.getId(), wjid.getFjdcflj(), 1);

        Map resultMap = new HashMap();

        resultMap.put("wordUrl", url);
        return HttpResult.ok(resultMap);

    }

    @AutoLog(value = "服务端-将word文件关闭并保存")
    @ApiOperation(value = "服务端-将word文件关闭并保存")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "质量体系文件id", required = true),
            @ApiImplicitParam(name = "isClose", value = "是否关闭文档，true=【关闭】")
    })
    @GetMapping(value = "getWebOfficeDownloadFile")
    public HttpResult<?> getWebOfficeDownloadFile(@RequestParam("id") String id,
                                                  @RequestParam(value = "isClose", defaultValue = "false") boolean isClose) {
        boolean isDel = false;
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null) {
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")) {
            return HttpResult.ok("保存关闭成功");
        }

        // 关闭文档
        Result closeResult1 = oaWebOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()) {
            return HttpResult.error(closeResult1.getMessage());
        }

        oaWebOfficeFIle.getWebOfficeDownloadFile2ByOazw(wjjl, wjjl.getFjdcflj(), isDel);

        // 关闭文档
        if (isClose) {
            return HttpResult.ok("保存关闭成功");
        } else {

            return HttpResult.ok("保存成功");
        }

    }


    @AutoLog(value = "客户端-文件在线编辑-打开文件")
    @ApiOperation(value = "客户端-文件在线编辑-打开文件")
    @ApiImplicitParam(name = "id", value = "质量体系文件id", required = true)
    @GetMapping(value = "openWjjl")
    public void openWjjl(@RequestParam("id") String id, HttpServletResponse response) {
        if (StringUtils.isBlank(id)) {
            log.error("【文件在线编辑】-文件id不能为空");
            return;
        }
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null) {
            log.error("【文件在线编辑】-文件id:{}的数据不存在", id);
            return;
        }
        if (StringUtils.isNotBlank(wjjl.getFjdcflj())) {
            oaLocalFileUploadUtils.ejzLocalFileURlByZdy(wjjl.getFjdcflj(), response);
        } else {
            log.error("【文件在线编辑】- 文件存放路径不存在");
            return;
        }
    }

    @AutoLog(value = "客户端-在线编辑-保存文件")
    @ApiOperation(value = "客户端-在线编辑-保存文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "docfile", value = "保存的文件", required = true),
            @ApiImplicitParam(name = "id", value = "质量体系文件id", required = true)
    })
    @PostMapping(value = "onLineSaveWjjl")
    public HttpResult<?> onLineSaveWjjl(@RequestParam("docfile") MultipartFile file, @RequestParam("id") String id) {
        if (StringUtils.isBlank(id)) {
            return HttpResult.error("质量体系文件id不能为空");
        }
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null) {
            return HttpResult.error("文件数据不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(wjjl);

        String oldCflj = wjjl.getFjdcflj(); // 旧文件存放路径

        String originalFilename = file.getOriginalFilename();

        if (originalFilename.lastIndexOf(".") == 0) {
            return HttpResult.error("文件不存在这个格式，请联系管理员");
        }
        // 文件类型
        String wjlx = ".doc";
        // 文件名

        String sjmc = wjjl.getFwjmc() + GetUuIdUtils.generateUuid();
        String wjccmc = sjmc + wjlx;
        String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
        String newDir = OaCommonFlowConstant.OA_ZW + "/" + nowDay;
        String cflj = "/" + newDir + "/" + wjccmc;

        oaLocalFileUploadUtils.uploadZdyzwFile(file, wjccmc, newDir); // 上传文件

        wjjl.setFwjlx(wjlx);
        wjjl.setFjdcflj(cflj);
        boolean flag = oaWjjlService.updateById(wjjl);
        if (flag) {
            oaLocalFileUploadUtils.deleteLocalFileUrlByZdy(oldCflj); // 删除旧的文件
        }

        return HttpResult.ok("保存文件成功");
    }

    /**
     * 数据转换
     *
     * @param oaWjjl
     */
    private void formatValue(OaWjjl oaWjjl) {
    }
}
